package cn.hchaojie.spring.day02.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class CategoryAspect {
	private static final String POINTCUT 
		= "execution(public * cn.hchaojie.spring.day02.service.CategoryService.findById(int))";

	private static final String POINTCUT2 
		= "execution(public * cn.hchaojie.spring.day02.service.CategoryService.findLike(..))";
	
	@Before(POINTCUT)
	public void beforeAdvice() {
		System.out.println("前置增强代码。。。");
		
//		throw new RuntimeException("当前用户没有权限！");
	}
	
	@After(POINTCUT)
	public void afterAdvice() {
		System.out.println("后置增强代码...");
	}
	
	/** 返回后通知，可以取到target对象的返回值 */
//	@AfterReturning(POINTCUT)
//	@AfterReturning(pointcut = POINTCUT)
	@AfterReturning(pointcut = POINTCUT, returning = "returnValue")
	public void afterReturning(Object returnValue) {
		System.out.println("返回后通知。。。target方法的返回值：" + returnValue);
	}
	
	/** 异常通知，target对象抛异常了，通知会生效 */
//	@AfterThrowing(POINTCUT2)
	@AfterThrowing(pointcut = POINTCUT2, throwing = "t")
	public void afterThrowingAdvice(Throwable t) {
		System.out.println("异常通知，异常消息：" + t.getMessage());
	}
	
	/** 环绕通知 
	 * @throws Throwable */
	@Around(POINTCUT)
	public Object aroundAdvice(ProceedingJoinPoint jp) throws Throwable {
		System.out.println("环绕通知的前置增强代码。。");
		long start = System.currentTimeMillis();
		
		Object result = jp.proceed();	// 相当于执行target对象的方法

		System.out.println("环绕通知的后置增强代码。。");
		long end = System.currentTimeMillis();
		System.out.println("方法耗时：" + (end - start));
		
		return result;
	}
}
